/*
 * Utility routines
 *
 * Copyright (c) 2007 Xaveer Leijtens
 *
 * This file is part of libMask.
 *
 * libMask is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * libMask is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with libMask.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "mask.h"

double RAD(double deg)
{
  return ((deg)/180.0*M_PI);
}

double DEG(double rad)
{ 
  return ((rad)*180.0/M_PI);
}
/* Map angle to [0, 2*pi> */
double map_0_2pi(double a)
{
  return a - 2 * M_PI * floor(a / M_PI / 2);
}

/* return radius of circle through three points and fill center coordinates */
double
radius_3pts(double x1, double y1, double x2, double y2, double x3, double y3,
  double *x0, double *y0)
{
  double t[2], u[2], v[2], w[2];
  double det, z, r;

  t[0] = (x1 + x2) / 2;
  t[1] = (y1 + y2) / 2;
  u[0] = (y2 - y1);
  u[1] = (x1 - x2);
  v[0] = (x2 + x3) / 2;
  v[1] = (y2 + y3) / 2;
  w[0] = (y3 - y2);
  w[1] = (x2 - x3);
  det = w[0]*u[1] - w[1]*u[0];
  if (fabs(det) < 1e-50) {
    fprintf(stderr, "radius_3pts: circle too large (det=%g)\n", det);
    exit(-1);
  }
  z = (w[0]*(v[1]-t[1]) - w[1]*(v[0]-t[0])) / det;
  *x0 = t[0] + z * u[0];
  *y0 = t[1] + z * u[1];
  r = sqrt((x1-*x0)*(x1-*x0) + (y1-*y0)*(y1-*y0));
  if (det < 0) r = -r;
  return r;
}

/* Show the current pointer with a symbol inidicating position, direction
 * and flip status.
 */
void show_cp(double l)
{
  double w;
  /* We use rect in stead of sw, to avoid side-effects of the extra length
   * when overlap is non-zero. show_cp() should have the precise starting
   * point.
   */
  w = l/20;
  push_cp();
  circle(w, l/2);
  push_cp();
    move(w,0,RAD(180),0);
    isosceles_triangle(w, w);
  pop_cp();
  skip(w);
  rect(l-w, w, 4, 6);
  rotate(RAD(135));
  rect(l/5, w, 4, 6);
  pop_cp();
}

